package com.iwhalecloud.uncc.scheduler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * @author zq
 * @date 2021/10/14 11:04
 * @description 基于Cron调度类
 */
@Slf4j
@Component
public class DynamicScheduler{

    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;

    private static Map<String, ScheduledFuture<?>> scheduledFutureMap = new ConcurrentHashMap<>();

    /**
     * 启动
     * @param scheduleTask
     * @param corn
     */
    public boolean start(ScheduleTask scheduleTask, String corn) {
//        log.info("定时归档任务启动！任务ID" + scheduleTask.getId());
        ScheduledFuture<?> scheduledFuture = taskScheduler.schedule(scheduleTask, new CronTrigger(corn));
        scheduledFutureMap.put(scheduleTask.getId(), scheduledFuture);
        return true;
    }

    /**
     * 取消
     * @param scheduleTask
     */
    public boolean cancel(ScheduleTask scheduleTask) {
        ScheduledFuture<?> scheduledFuture =  scheduledFutureMap.get(scheduleTask.getId());
        if (scheduledFuture != null && !scheduledFuture.isCancelled()) {
            scheduledFuture.cancel(false);
        }
        scheduledFutureMap.remove(scheduleTask.getId());
        return true;
    }

    /**
     * 修改
     * @param scheduleTask
     * @param corn
     */
    public boolean reset(ScheduleTask scheduleTask, String corn) {
        //先取消定时任务
        cancel(scheduleTask);
        //然后启动新的定时任务
        start(scheduleTask, corn);
        return true;
    }


}
